package com.banciyuan.bcywebview.biz.qqapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.register.PhoneRegisterActivity;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sns.SnsMemory;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.QQMessage;

public class QQEntryActivity extends Activity {
    private Tencent mTencent;
    private BaseUiListener baseUiListener;
    private QQMessage mQQMessage;
    private RequestQueue mQueue;
    private String expires;
    private String unid;
    private String qqName;
    private String qqToken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTencent = Tencent.createInstance(MyConstants.QQ_LOGIN_APP_ID, getApplicationContext());
        baseUiListener = new BaseUiListener();
        initArgs();
    }

    public void initArgs() {
        mQQMessage = new QQMessage();
        mQueue = VolleyQueue.getRquest(this);
        if (!mTencent.isSessionValid()) {
            mTencent.login(this, MyConstants.QQ_SCOPE, baseUiListener);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Tencent.onActivityResultData(requestCode, resultCode, data, baseUiListener);
        } else {
            finish();
        }
    }

    private void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    private void getUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            UserInfo mInfo = new UserInfo(QQEntryActivity.this, mTencent.getQQToken());
            mInfo.getUserInfo(new UserInfoListener());
        }
    }


    private void qqLogin() {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                String result = dealQQJson(response);
                if (result == HttpUtils.UPLOAD_SUCCESS) {
                    setResult(RESULT_OK);
                    finish();
                } else if (result == HttpUtils.UPLOAD_NODATA) {
                    gotoUtil.replaceAct(QQEntryActivity.this, PhoneRegisterActivity.class, false, qqName, true);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        };

        List<BcyPair> params = new ArrayList<>();
        params.add(new BcyPair(HttpUtils.QQ_PARAM_ETIME, expires));
        params.add(new BcyPair(HttpUtils.SINA_PARAM_UID, unid));
        if (!TextUtils.isEmpty(qqName)) {
            params.add(new BcyPair(HttpUtils.QQ_PARAM_NAME, qqName));
            SnsMemory.mQQMsg.qqName = qqName;
        }
        params.add(new BcyPair(HttpUtils.QQ_PARAM_TOKEN, qqToken));
        Map<String, String> map = HttpUtils.getData(params);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST,
                HttpUtils.BASE_URL + UserApi.getQqlogin(), map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
    }

    private String dealQQJson(String result) {
        try {
            JSONObject response = new JSONObject(result);
            int status = response.getInt(HttpUtils.UPLOAD_STATUS);
            if (status == 1) {
                UserDataHelper.Login(response.getJSONObject(HttpUtils.UPLOAD_DATA), this);
                return HttpUtils.UPLOAD_SUCCESS;
            } else {
                MyToast.show(this, String.format(MyConstants.TOAST_FORMAT, response.getString(HttpUtils.UPLOAD_DATA)));
                return HttpUtils.UPLOAD_NODATA;
            }
        } catch (JSONException e) {
            return HttpUtils.UPLOAD_ERROR;
        }
    }

    private class UserInfoListener implements IUiListener {

        @Override
        public void onError(UiError e) {
            finish();
        }

        @Override
        public void onCancel() {
            finish();
        }

        @Override
        public void onComplete(Object response) {
            try {
                JSONObject json = (JSONObject) response;
                int ret = json.optInt("ret");
                if (ret == 0) {
                    qqName = json.optString("nickname");
                    qqLogin();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(Object response) {
            //V2.0版本，参数类型由JSONObject 改成了Object,具体类型参考api文档
            try {
                try {
                    JSONObject json = new JSONObject(response.toString());
                    initOpenidAndToken(json);
                    unid = StringUtil.getFromJson(json, "openid");
                    expires = StringUtil.getFromJson(json, "expires_in");
                    qqToken = StringUtil.getFromJson(json, "access_token");
                    mQQMessage.unid = unid;
                    mQQMessage.expires = expires;
                    mQQMessage.qqToken = qqToken;
                    SnsMemory.mQQMsg = mQQMessage;
                    getUserInfo();
                } catch (Exception e) {
                    MyToast.show(QQEntryActivity.this, getString(R.string.author_fail));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError e) {
            finish();
            Log.d("onError", "qq BaseUiListener onError");
        }

        @Override
        public void onCancel() {
            finish();
            Log.d("onCancel", "qq BaseUiListener onCancel");
        }
    }

}